package models

import (
	"github.com/jinzhu/gorm"
	"mz_water/entity"
	"mz_water/util"
	"time"
)

type Wx_user struct {
	Openid     string    `gorm:"column:AppId"`
	NickName   string    `gorm:"column:NickName" json:"nick_name" `
	Gender     string    `gorm:"column:Gender" json:"gender" `
	Country    string    `gorm:"column:Country" json:"country" `
	Province   string    `gorm:"column:Province" json:"province"`
	City       string    `gorm:"column:City" json:"city"`
	AvatarUrl  string    `gorm:"column:AvatarUrl" json:"avatar_url"`
	UpdateTime time.Time `gorm:"column:UpdateTime" json:"update_time"`
	CreateTime time.Time `gorm:"column:CreateTime" json:"create_time"`
}

func (w Wx_user) TableName() string {
	return "mz_wx_user"
}

func WxLogin(app *entity.APPSECRET) (u *Wx_user, e error) {
	users := &Wx_user{Openid: app.Openid}
	err := util.GetDb().First(users).Error
	// 判断此用户有没有使用过小程序
	if gorm.IsRecordNotFoundError(err) {
		if err := util.GetDb().Create(users).Error; err != nil {
			return users, err
		}
	} else if err != nil {
		// sql 执行失败
		return users, err
	}
	return users, err
}

func CreateUser(user Wx_user) (u *Wx_user, err error) {
	users := &Wx_user{
		Openid:     user.Openid,
		NickName:   user.NickName,
		Gender:     user.Gender,
		Country:    user.Country,
		Province:   user.Province,
		City:       user.City,
		AvatarUrl:  user.AvatarUrl,
		UpdateTime: time.Now(),
		CreateTime: time.Now(),
	}
	err = util.GetDb().Model(users).Where("AppId = ?", user.Openid).Update(users).Error
	if err != nil {
		return users, err
	}

	return users, err
}
